package cn.vplay.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class PluploadService {

	 public static void upload(Plupload plupload,
			 File pluploadDir,HttpSession session){ 
			UUID uuid = UUID.randomUUID();
			String[] fileNames = plupload.getName().split("\\.");
	        String fileName =uuid.toString()+"."+fileNames[1];
	        session.setAttribute("uuid", uuid.toString());
	        session.setAttribute("exMv", fileNames[1]);
	        upload(plupload,pluploadDir,fileName);  
	    }  
	  
	    private static void upload(Plupload plupload,File pluploadDir,String fileName){  
	  
	        int chunks = plupload.getChunks();   //获取总的碎片数
	        int nowChunk = plupload.getChunk();   //获取当前碎片(从0开始计数)
	  
	        MultipartHttpServletRequest multipartHttpServletRequest  = (MultipartHttpServletRequest)plupload.getRequest();
	        MultiValueMap map = multipartHttpServletRequest.getMultiFileMap();
	  
	        if(map!=null){  
	            try{  
	                Iterator iterator = map.keySet().iterator();  
	                while(iterator.hasNext()){
	                    String key = (String) iterator.next(); 
	                    List<MultipartFile> multipartFileList = (List<MultipartFile>) map.get(key);
	                    for(MultipartFile multipartFile:multipartFileList){
							//因为只存在一个值,所以最后返回的既是第一个也是最后一个值
							plupload.setMultipartFile(multipartFile);
							//创建新目标文件
	                        File targetFile = new File(pluploadDir+"/"+fileName);
							//当chunks>1则说明当前传的文件为一块碎片，需要合并
	                        if(chunks>1){
								//需要创建临时文件名，最后再更改名称
	                            File tempFile = new File(pluploadDir.getPath()+"/"+multipartFile.getName());
								//如果chunk==0,则代表第一块碎片,不需要合并
	                            savePluploadFile(multipartFile.getInputStream(),tempFile,nowChunk==0?false:true);
	  							//上传并合并完成，则将临时名称更改为指定名称
	                            if(chunks-nowChunk==1){
	                                tempFile.renameTo(targetFile);  
	                            }  
	                        }  
	                        else{
								//否则直接将文件内容拷贝至新文件
	                            multipartFile.transferTo(targetFile);  
	                        }  
	                    }  
	                }  
	            }  
	            catch (IOException e){  
	                e.printStackTrace();  
	            }  
	        }  
	    }
	/**
	 * 保存上传文件，兼合并功能
	 */
	    private static void savePluploadFile(InputStream inputStream,File tempFile,boolean flag){  
	        OutputStream outputStream = null;  
	        try {  
	            if(flag==false){  
	                outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
	            }  
	            else{  
		                outputStream = new BufferedOutputStream(new FileOutputStream(tempFile,true));
	            }  
	            byte[] bytes = new byte[1024];  
	            int len = 0;
				//写入文件
	            while ((len = (inputStream.read(bytes)))>0){  
	                outputStream.write(bytes,0,len);  
	            }  
	        }  
	        catch (FileNotFoundException e){  
	            e.printStackTrace();  
	        }  
	        catch (IOException e){  
	            e.printStackTrace();  
	        }  
	        finally {    //关闭输入输出流
	            try{  
	                outputStream.close();  
	                inputStream.close();  
	            }  
	            catch (IOException e){  
	                e.printStackTrace();  
	            }  
	        }  
	    }  
}
